using System.Net.WebSockets;
using System.Text;
using Microsoft.AspNetCore.Mvc;

namespace WebSocketServer.Controllers;

public class WebSocketController : ControllerBase {
    [HttpGet("/ws")]
    public async Task Get() {
        if (HttpContext.WebSockets.IsWebSocketRequest) {
            using var webSocket =
                await HttpContext.WebSockets.AcceptWebSocketAsync();
            await Echo(webSocket);
        } else {
            HttpContext.Response.StatusCode = StatusCodes.Status400BadRequest;
        }
    }

    private static async Task Echo(WebSocket webSocket) {
        var buffer = new byte[1024 * 4];
        var receiveResult = await webSocket.ReceiveAsync(
            new ArraySegment<byte>(buffer), CancellationToken.None);

        while (!receiveResult.CloseStatus.HasValue) {
            var message = $"You sent me {receiveResult.Count} bytes of data. ";
            var messageBytes = Encoding.Default.GetBytes(message);

            await webSocket.SendAsync(new ArraySegment<byte>(messageBytes),
                WebSocketMessageType.Text, receiveResult.EndOfMessage,
                CancellationToken.None);

            receiveResult = await webSocket.ReceiveAsync(
                new ArraySegment<byte>(buffer), CancellationToken.None);
        }

        await webSocket.CloseAsync(receiveResult.CloseStatus.Value,
            receiveResult.CloseStatusDescription, CancellationToken.None);
    }
}